<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="1400px"
      :title="parameter.text"
      wrapClassName="add-modal-container"
      @cancel="closeModal()"
    >
      <div class="curve-modal-body">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <a-row :gutter="0">
            <a-col :span="12">
              <a-form-model-item label="项目名称" prop="uuid">
                <a-select
                  showSearch
                  :filter-option="filterOption"
                  v-model="form.uuid"
                  :loading="projectLoading"
                  placeholder="请选择项目名称"
                  @change="projectChange($event)"
                  :disabled="parameter.text == '编辑' ? true : false"
                >
                  <a-select-option
                    :value="item.uuid"
                    v-for="item in projectSoucre"
                    :key="item.uuid"
                  >
                    {{ item.proName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="评级" prop="grade">
                <a-select
                  showSearch
                  :filter-option="filterOption"
                  :loading="gradeLoading"
                  placeholder="请选择评级"
                  v-model="form.grade"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in gradeSoucre"
                    :key="item.uuid"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-form-model-item label="项目地址" prop="provinceCode">
              <a-col :span="4" style="padding-right:10px">
                <a-select
                  showSearch
                  :filter-option="filterOption"
                  v-model="form.provinceCode"
                  placeholder="请选择省"
                  @change="provinceChange"
                >
                  <a-select-option
                    :value="item.code"
                    v-for="(item, index) in provinceSource"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="4" style="padding-right:10px">
                <a-select
                  showSearch
                  :filter-option="filterOption"
                  v-model="form.cityCode"
                  placeholder="请选择市"
                  @change="cityChange"
                >
                  <a-select-option
                    :value="item.code"
                    v-for="(item, index) in citySource"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="4" style="padding-right:10px">
                <a-select
                  v-model="form.areaCode"
                  placeholder="请选择区县"
                  showSearch
                  :filter-option="filterOption"
                >
                  <a-select-option
                    :value="item.code"
                    v-for="(item, index) in areaSource"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="12">
                <a-input
                  placeholder="请输入详细地址"
                  v-model.trim="form.address"
                />
              </a-col>
            </a-form-model-item>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="8">
              <a-form-model-item label="开工时间" prop="startDate">
                <a-date-picker
                  style="width: 100%"
                  v-model="form.startDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  placeholder="请选择开工时间"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="完工时间" prop="endDate">
                <a-date-picker
                  style="width: 100%"
                  v-model="form.endDate"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  placeholder="请选择完工时间"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="项目类型" prop="proType">
                <a-select
                  showSearch
                  :filter-option="filterOption"
                  :loading="projectTypeLoading"
                  placeholder="请选择项目类型"
                  v-model="form.proType"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in projectTypeSoucre"
                    :key="item.uuid"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item label="项目概况" prop="introduction">
                <a-input
                  placeholder="请输入联系方式"
                  v-model.trim="form.introduction"
                  type="textarea"
                  :rows="4"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="0">
            <a-col :span="24">
              <a-form-model-item
                label="文件"
                prop="file"
                :rules="{
                  required: true,
                  message: '请选择文件',
                }"
              >
                <bjUploadFile
                  :count="10"
                  v-model="form.file"
                  @download="downloadFile($event)"
                  @change="upLoadFile($event)"
                  @preview="viewFile($event)"
                  :replaceFields="{
                    fileName: 'fileName',
                    fileSize: 'fileSize',
                    fileType: 'fileType',
                  }"
                ></bjUploadFile>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="curve-modal-footer">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button type="primary" @click="onSubmit()" :loading="buttonLoading">
          确定
        </a-button>
      </div>
    </a-modal>

    <!-- 附件预览弹窗 -->
    <previewModal
      :visible.sync="previewVisible"
      :loading="previewLoading"
      ref="previewModal"
    ></previewModal>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getToken } from "@/utils/TopVUI";
import { axios } from "@/utils/request";
import { downloadDfs } from "@/utils/TopVUI";
import areaData from "@/components/_utils/area-json.js";
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
import previewModal from "@/pages/document/minio/previewModal";
import { getPZGCProList } from "@/api/qualityEngineering";
export default {
  name: "addModal",
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    parameter: {
      type: Object,
      default: {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  data() {
    return {
      buttonLoading: false,
      form: {
        //项目名称
        uuid: undefined,
        grade: undefined,
        proType: undefined,
        //项目所在地
        provinceCode: undefined,
        cityCode: undefined,
        areaCode: undefined,
        address: "",
        //开工时间
        startDate: "",
        //完工时间
        endDate: "",
        introduction: "",
        file: [],
      },
      rules: {
        uuid: [
          { required: true, message: "请选择项目名称", trigger: "change" },
        ],
        grade: [{ required: true, message: "请选择评级" }],
        provinceCode: [{ required: true, message: "请选择项目所在地" }],
        startDate: [{ required: true, message: "请选择开工时间" }],
        endDate: [{ required: true, message: "请选择完工时间" }],
        proType: [{ required: true, message: "请选择项目类型" }],
        introduction: [{ required: true, message: "请输入项目概况" }],
      },
      //项目下拉框
      projectSoucre: [],
      projectLoading: false,
      //项目类型下拉框
      projectTypeSoucre: [],
      projectTypeLoading: false,
      //评级
      gradeSoucre: [],
      gradeLoading: false,
      //省市区
      provinceSource: areaData,
      citySource: [],
      areaSource: [],
      previewVisible: false,
      previewLoading: false,
    };
  },
  methods: {
    getDetail() {
      this.form.uuid = this.parameter.uuid;
      this.getProjectInfo();
    },
    //下载附件
    downloadFile(file) {
      let { url } = file;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },

    // 预览附件
    viewFile(file) {
      let { url } = file;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewVisible = true;
    },

    //上传附件
    upLoadFile({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["file"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(
            this.form.file[this.form.file.length - 1],
            "dfsFileUuid",
            res.dfsFileUuid
          );
          this.$set(this.form.file[this.form.file.length - 1], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form["file"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["file"][index], "loading", false);
        });
    },

    projectChange() {
      this.getProjectInfo();
      this.$forceUpdate();
    },

    getProjectInfo() {
      return new Promise((resolve, reject) => {
        let { uuid } = this.form;
        this.$post("/mdata/sysProject/getDetailByUuid", {
          varchar: uuid,
        })
          .then((res) => {
            this.form.startDate = res.startDate;
            this.form.endDate = res.endDate;
            this.form.grade = res.grade;
            this.form.proType = res.proType;
            this.form.introduction = res.introduction;
            //项目所在地
            this.form.address = res.address;
            let str = res?.remark ?? "";
            let arr = str.split(",");
            let provCode = arr?.[0] ?? "";
            let cityCode = arr?.[1] ?? "";
            let areaCode = arr?.[2] ?? "";
            this.citySource =
              this.provinceSource.find((item) => item.code == provCode)
                ?.children || [];
            this.areaSource =
              this.citySource.find((item) => item.code == cityCode)?.children ||
              [];
            this.form.provinceCode = provCode ? provCode.toString() : undefined;
            this.form.cityCode = cityCode ? cityCode.toString() : undefined;
            this.form.areaCode = cityCode ? areaCode.toString() : undefined;
            //附件
            this.form.file = [];
            let files = JSON.parse(res.fileInfos ?? "[]");
            files.forEach((v) => {
              let lastIdx = v.name.lastIndexOf(".");
              let fileType = "." + v.name.substring(lastIdx + 1);
              this.form.file.push({
                fileName: v.name,
                fileType: fileType,
                fileSize: v.size,
                dfsFileUuid: v.uid,
                url: v.url,
              });
            });
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },

    getData() {
      Promise.all([
        this.getProjectData(),
        this.getGradeList(),
        this.getProjectType(),
      ])
        .then()
        .finally((_) => {
          let { text } = this.parameter;
          if (text == "编辑") {
            this.getDetail();
          }
        });
    },

    //查询项目下拉框
    getProjectData() {
      this.projectLoading = true;
      return new Promise((resolve, reject) => {
        getPZGCProList({ type: 3 })
          .then((res) => {
            this.projectSoucre = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.projectSoucre = [];
            reject();
          })
          .finally((_) => {
            this.projectLoading = false;
          });
      });
    },
    //项目类型
    getProjectType() {
      this.projectTypeLoading = true;
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "projectType",
        })
          .then((res) => {
            let { data } = res;
            this.projectTypeSoucre = data || [];
            resolve();
          })
          .catch((_) => {
            this.projectTypeSoucre = [];
            reject();
          })
          .finally((_) => {
            this.projectTypeLoading = false;
          });
      });
    },

    //查询评级
    getGradeList() {
      this.gradeLoading = true;
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "pzgcGrade",
        })
          .then((res) => {
            let { data } = res;
            this.gradeSoucre = data || [];
            resolve();
          })
          .catch((_) => {
            this.gradeSoucre = [];
            reject();
          })
          .finally((_) => {
            this.gradeLoading = false;
          });
      });
    },

    //选择省
    provinceChange(e) {
      this.form.cityCode = undefined;
      this.form.areaCode = undefined;
      this.citySource = [];
      this.areaSource = [];
      this.citySource =
        this.provinceSource.find((item) => item.code == e)?.children || [];
    },

    //选择市
    cityChange(e) {
      this.form.areaCode = undefined;
      this.areaSource = [];
      this.areaSource =
        this.citySource.find((item) => item.code == e)?.children || [];
    },

    //提交
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          let { form } = this;
          let ids = form.file.map((item) => item.dfsFileUuid);
          let formJson = {
            //项目名称
            uuid: form.uuid,
            grade: form.grade,
            proType: form.proType,
            //项目所在地
            provinceCode: form.provinceCode,
            cityCode: form.cityCode,
            areaCode: form.areaCode,
            address: form.address,
            remark: `${form.provinceCode},${form.cityCode},${form.areaCode}`,
            //开工时间
            startDate: form.startDate,
            //完工时间
            endDate: form.endDate,
            introduction: form.introduction,
            fileIds: ids.toString(),
          };
          axios
            .post(`/mdata/sysProject/submitProject`, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.closeModal();
                this.$parent.getTableData();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.buttonLoading = false;
            });
        }
      });
    },

    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //重置表单
    resetForm() {
      this.form = {
        //项目名称
        uuid: undefined,
        grade: undefined,
        proType: undefined,
        //项目所在地
        provinceCode: undefined,
        cityCode: undefined,
        areaCode: undefined,
        address: "",
        //开工时间
        startDate: "",
        //完工时间
        endDate: "",
        introduction: "",
        file: [],
      };
      this.$refs.ruleForm.resetFields();
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    selectContainer(triggerNode) {
      return triggerNode.parentNode;
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .ant-modal-header {
    position: relative;
    .ant-modal-title {
      &::before {
        content: "";
        position: absolute;
        top: 18px;
        left: 10px;
        background-color: @primary-color;
        height: 17px;
        width: 5px;
      }
    }
  }

  .curve-modal-body {
    padding: 14px;
    max-height: 700px;
    overflow: auto;
  }
  .curve-modal-footer {
    padding: 10px 16px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #e8e8e8;
    border-radius: 0 0 4px 4px;
    button {
      &:last-child {
        margin-left: 20px;
      }
    }
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 150px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
  .bj-upload-file {
    .choosed-file-warp {
      width: 1220px;
    }
  }
}
</style>
